package gw.com.android.presenter;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;

import com.gwtsz.gts2.hx.R;

import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.presenter.http.Https;
import gw.com.android.ui.AdvertiseActivity;
import gw.com.android.ui.MainActivity;
import gw.com.android.utils.ThreadPool;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;
import www.com.library.app.Logger;
import www.com.library.util.DeviceUtil;

/**
 * 广告页处理类
 *
 * @author jett
 * @since 2017-09-05.
 */
@SuppressWarnings("ResultOfMethodCallIgnored")
public class AdverPagePresenter {

    private static final String TAG = "AdverPagePresenter";

    public static AdverPagePresenter instance;

    private boolean needDownload = true; // 是否需要下载广告
    private boolean completed = false;  //是否下载完成

    private boolean enable = true;  // 该功能是否启用
    private boolean awake = false;  // 后台唤醒是否显示广告
    private long duration = 3000L;  //广告时长
    private long frequency;         //显示频率

    public String linkUrl;  //链接跳转
    public String title;        // 链接标题
    private String url;     //下载地址
    private File imageFile; //  广告图片文件
    private OnCompletedListener listener;

    private AdverPagePresenter() {
        JSONObject jsonObject = ConfigUtil.instance().mConfigObject.optJSONObject(ConfigType.ADVERTISEMENT_PAGE_TAG);
        if (jsonObject != null) {
            enable = jsonObject.optBoolean(ConfigType.CONFIG_TYPE_HAS_NEED_TAG, true);
            awake = jsonObject.optBoolean("awake", false);
            duration = jsonObject.optLong("durationMillisecond", 3000L);
            frequency = jsonObject.optLong("frequencyMinute", 0);
        }
        if (!enable) {
            needDownload = false;
            Logger.i(TAG, "advertise page is disable");
        }
        if (checkFrequency()) {
            needDownload = false;
        }
    }

    public static AdverPagePresenter getInstance() {
        if (instance == null) {
            synchronized (AdverPagePresenter.class) {
                if (instance == null) {
                    instance = new AdverPagePresenter();
                }
            }
        }
        return instance;
    }

    public boolean isCompleted() {
        return completed;
    }

    public void preload() {
        Logger.i(TAG, "preload..");
        if (!needDownload()) {
            Logger.i(TAG, "preload..  not need");
            return;
        }
        ThreadPool.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                load();
                // 先下载广告页，再下载启动页
                LaunchPagePresenter.preload();
            }
        });
    }

    /**
     * 检查广告显示频率
     *
     * @return if true 不需要再次显示广告
     */
    private boolean checkFrequency() {
        long currentTime = System.currentTimeMillis();
        long lastTime = GTConfig.instance().getLongValue("advertisePage", -1);
        if (lastTime > 0 && frequency > 0 && Math.abs(currentTime - lastTime) < frequency * 60 * 1000) {
            Logger.i(TAG, "needn't load advertise for this time. frequency is " + frequency + " minute");
            return true;
        }
        return false;
    }

    private int getLastAccountType() {
        int type = GTConfig.ACC_TYPE_GUEST;
        if (GTConfig.instance().getBooleanValue(GTConfig.PREF_AUTO_LOGIN, true)) {
            String loginName = GTConfig.instance().getLoginName();
            if (DeviceUtil.instance().isPhone(loginName)) {
                type = GTConfig.instance().getLastPhoneLoginType(loginName);
            } else {
                if (loginName.startsWith(ConfigUtil.instance().mConfigObject.optString(ConfigType.PREFIX_DEMO_ACCOUNT))) {
                    type = GTConfig.ACC_TYPE_DEMO;
                } else {
                    type = GTConfig.ACC_TYPE_REAL;
                }
            }
        }
        return type;
    }

    private void load() {
        Logger.i(TAG, "load advertise");
        int type = getLastAccountType();
        Logger.i(TAG, "last account type = " + type);
        Map<String, AdsData> allAds = AdsConfigPresenter.getInstance().getAllAds(type);
        parse(allAds);
        if (TextUtils.isEmpty(url)) {
            needDownload = false;
            Logger.i(TAG, "load .. url is empty .");
            return;
        }
        Logger.i(TAG, "generate local temp file");
        File imageFile = getImageFile();
        if (imageFile.exists()) {
            imageFile.delete();
        }
        try {
            imageFile.createNewFile();
        } catch (IOException e) {
            Logger.e(TAG, e);
        }
        download(imageFile);
        completed = true;
        if (this.listener != null) {
            listener.onCompleted();
        }
        clearCache();
    }

    /**
     * 下载广告图片
     */
    private void download(File outFile) {
        Logger.i(TAG, "fetch advertise now");
        FileOutputStream out = null;
        Request request = new Request.Builder().url(url).build();
        Call call = new Https().getOkHttpClient().newCall(request);
        try {
            Response response = call.execute();
            if (response.code() < 200 || response.code() >= 300) {
                Logger.i(TAG, "response code error. code = " + response.code());
                return;
            }
            InputStream in = response.body().byteStream();
            out = new FileOutputStream(outFile);
            int len;
            byte[] buff = new byte[2048];
            while ((len = in.read(buff)) != -1) {
                out.write(buff, 0, len);
            }
            out.flush();
        } catch (IOException e) {
            Logger.e(TAG, e);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException ignore) {
                }
            }
        }
        Logger.i(TAG, "fetch advertise completed");
    }

    /**
     * 清除上次残余的缓存图片
     */
    private void clearCache() {
        Logger.i(TAG, "clear cache.");
        File dir = getImageDir();
        File[] files = dir.listFiles();
        for (File f : files) {
            if (f != null && !f.getName().equals(getImageFile().getName())) {
                f.delete();
            }
        }
    }

    public File getImageFile() {
        if (imageFile == null) {
            File dir = getImageDir();
            if (!dir.exists()) {
                dir.mkdirs();
            }
            int index;
            if (!TextUtils.isEmpty(url) && (index = url.lastIndexOf("/")) > 0) {
                String name = url.substring(index, url.length());
                imageFile = new File(dir, name);
            } else {
                imageFile = new File(dir, "temp_ad.png");
            }
        }
        return imageFile;
    }

    private File getImageDir() {
        return new File(AppMain.getApp().getCacheDir(), "advertise");
    }

    /**
     * 广告显示后回调
     */
    public void onAdvertiseShowed() {
        GTConfig.instance().setLongValue("advertisePage", System.currentTimeMillis());
    }

    public long getDuration() {
        return duration;
    }

    private void parse(Map<String, AdsData> allAds) {
        if (allAds != null) {
            AdsData adsData = allAds.get(AdsConfigPresenter.TYPE_ADVER_PAGE);
            if (adsData != null && adsData.adPics != null && !adsData.adPics.isEmpty()) {
                AdsData.PicData picData = adsData.adPics.get(0);
                if (picData != null) {
                    linkUrl = picData.link;
                    title = picData.title;
                    url = picData.url;
                    Logger.i(TAG, "parse advertise success");
                }
            }
        }
    }

    public boolean needDownload() {
        return needDownload;
    }

    /**
     * 从后台唤起时，是否显示广告
     */
    public void onAwake(Activity activity) {
        if (!awake) {
            Logger.i(TAG, "needn't show advertise when awake from background");
            return;
        }
        if (checkFrequency()) {
            return;
        }
        if (!(activity instanceof MainActivity)) {
            return;
        }
        if (completed && imageFile != null && imageFile.exists()) {
            activity.startActivity(new Intent(activity, AdvertiseActivity.class).putExtra("awake", true));
        }
    }

    public void setOnCompletedListener(OnCompletedListener listener) {
        this.listener = listener;
    }

    public interface OnCompletedListener {
        void onCompleted();
    }

}
